<?php
namespace app\admin\model;
use app\common\model\Model;
use think\Db;
use think\Loader;

//  model 类
class OrderModel extends Model
{
    const TABLE_NAME = 'order_info';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_4;

    protected $name = self::TABLE_NAME;

    const STATUS_UN_PAY =1; //没有支付
    const STATUS_PAY=2; //已支付，但没有 发货
    const STATUS_DELIVERY=3;//已发货
    const STATUS_COMPLETE =4; //已完成
    const STATUS_CANCEL =5; // 已取消

    public static function getOrderInfo($id){

        return self::commonQuery('order',self::CACHE_EXPIRE_LEVEL)->where('order_id',$id)->find();

    }

    public static function getOrderDetail($id)
    {
        return self::commonQuery(self::TABLE_NAME)->where('order_info_id',$id)->find();

    }
    // 根据传入的 订单详情id 字符串获取 各个详情订单信息
    public function getOrderInfoList($ids=''){
        if(!$ids){
            return false;
        }

        $res=self::commonQuery(self::TABLE_NAME)->where('order_info_id','in',$ids)->select();
        return $res?$res:[];

    }
    

    // 导出  Excel 
    public static function getOrderExcel(){

        loader::import('PHPExcel.PHPExcel', EXTEND_PATH);
        loader::import('PHPExcel.PHPExcel.Writer.Excel5', EXTEND_PATH);
        loader::import('PHPExcel.PHPExcel.IOFactory', EXTEND_PATH);

        $objPHPExcel = new \PHPExcel;


        $fileName = 'order_List' . date('Y_m_d_H_i_s') . '.xls';

        // $list = Db::table($table)->field($fields)->select();
        $list = Db::view('order',['order_id','order_sn','add_time','delivery_time','receive_time','is_coupon','coupon_sum','nominal_amount','actual_amount','status'])->view('user',['user_name'],'user.user_id = order.user_id')->view('address',['address','house_number'],'address.address_id = order.address_id')->select();

        // return $list;
        foreach ($list as $key => $value) {

            $list[$key]['add_time']=date('Y-m-d H:i:s',$list[$key]['add_time']);
            $list[$key]['delivery_time']=date('Y-m-d H:i:s',$list[$key]['delivery_time']);
            $list[$key]['receive_time']=date('Y-m-d H:i:s',$list[$key]['receive_time']);

            if($list[$key]['status'] == 1){
                $list[$key]['status'] = '未付款';
            }else if($list[$key]['status'] == 2){
                $list[$key]['status'] = '已付款，未发货';
            } else if ($list[$key]['status'] == 3) {
                $list[$key]['status'] = '已发货';
            } else if ($list[$key]['status'] == 4) {
                $list[$key]['status'] = '已完成';
            } else if ($list[$key]['status'] == 5) {
                $list[$key]['status'] = '已取消';
            }
        }

        // return $list;
        $headArr= array('编号','订单号', '下单时间', '派送时间','收货时间','是否使用优惠券','优惠金额','名义总价','实际总价','订单状态','用户姓名','地址信息','地址详细信息');

        $key = ord('A');
        for ($i = 0; $i < count($headArr); $i++) {
            $colnum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colnum . '1', $headArr[$i]);
            $key++;
        }

        if ($list) {
            $mark = 2; //从第二行开始 
            $objActSheet = $objPHPExcel->getActiveSheet();
            foreach ($list as $key => $val) {
                $span = ord('A');
                foreach ($val as $k => $v) {
                    $j = chr($span);
                    $objActSheet->setCellValue($j . $mark, $v);
                    $span++;
                }
                $mark++;
            }
        }

        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
    }

    public static function orderList($keyword = "", $order_type = '1', $search_type_of_time='', $atime = '', $ztime = '' ,$status='0'){


        $where='';
        if($keyword){

            // 订单号查询
            $where['order_sn']=['like',"%$keyword%"];
        }

        // 筛选未发货订单表
        if($status != '0'){
            $where['status'] = $status;
        }


        if($order_type == 1){
            $order_type='add_time desc';
        }else if($order_type == 2){
            $order_type="add_time ";
        }else if ($order_type == 3) {
            $order_type = "delivery_time desc";
        } else if ($order_type == 4) {
            $order_type = "delivery_time ";
        } else if ($order_type == 5) {
            $order_type = "receive_time desc";
        } else if ($order_type == 6) {
            $order_type = "receive_time ";
        } 

        // 搜索时间
        /*
        @ search_type_of_time 1 下单 2发货 3收货
         */

        $search_type_of_time_fields=[1=>'add_time',2=>'delivery_time',3=>'receive_time'];


        if(isset($search_type_of_time_fields[$search_type_of_time]))
        {

            $atime_stamp =0 ;
            $ztime_stamp=0;
            $oneday=86400;

            if ($atime != '' && $search_type_of_time != '') {
                $atime_stamp = strtotime($atime);

            }
            if ($ztime != '' && $search_type_of_time != '') {
                $ztime_stamp = strtotime($ztime);
            }

            if(!empty($atime_stamp) && !empty($ztime_stamp))
            {
                $where[$search_type_of_time_fields[$search_type_of_time]]=[['>', $atime_stamp], ['<', $ztime_stamp + $oneday],'and'];
            }else if(!empty($atime_stamp))
            {
                $where[$search_type_of_time_fields[$search_type_of_time]]=['>',$atime_stamp];
            }else if(!empty($ztime_stamp))
            {
                $where[$search_type_of_time_fields[$search_type_of_time]]=['<',$ztime_stamp + $oneday];
            }
        }


        return self::commonQuery('order_info')->where($where)->order($order_type);

    }

    public static function handleOrderInfo($info)
    {
        $order_info = self::getOrderInfo($info['order_id']);
        $info = array_merge($info,$order_info);
        $user_info = UserModel::getUserInfo($info['user_id']);

        $address_info = UserModel::getExtendInfo($info['user_id'],UserModel::CACHE_EXPIRE_LEVEL_1);


        $info['user_name']=$user_info['user_name'];
        $info['user_phone']=$user_info['user_phone'];
        $info['address']=$address_info['address'];

        $info['add_time']=date('Y-m-d H:i:s',$info['add_time']);
        $info['delivery_time']=$info['delivery_time']?date('Y-m-d H:i:s',$info['delivery_time']):'------';
        $info['receive_time']= $info['receive_time']?date('Y-m-d H:i:s',$info['receive_time']):'------';


        $goods_info =GoodsModel::getGoodsInfoById($info['goods_id']);
        $info['goods_info']= $goods_info['goods_name'].$goods_info['goods_sn'];

        return $info;
        
    }
    //获取 当前状态
    public static function getStatusForUpdate($id)
    {
        $sql = "select user_id,goods_id,num,status from order_info where order_info_id = $id for UPDATE ";
        $res = self::query($sql);
        return empty($res)?[]:$res[0];
    }
    //更新为 已支付状态
    public static function updatePayStatus($id)
    {
        return self::commonQuery(self::TABLE_NAME)
            ->where(['order_info_id'=>$id])
            ->setField('status',self::STATUS_PAY);
    }
    //更新 为 已发货状态
    public static function updateDeliveryStatus($id)
    {
        return self::commonQuery(self::TABLE_NAME)
              ->where(['order_info_id'=>$id])
              ->update(['delivery_time'=>time(),'status'=>self::STATUS_DELIVERY]);
    }
    //更新为 已完成 状态
    public static function updateCompleteStatus($id)
    {
        return self::commonQuery(self::TABLE_NAME)
            ->where(['order_info_id'=>$id])
            ->update(['receive_time'=>time(),'status'=>self::STATUS_COMPLETE]);
    }
  //更新为 取消 状态
    public static function updateCancelStatus($id)
    {
        return self::commonQuery(self::TABLE_NAME)
            ->where(['order_info_id'=>$id])
            ->update(['cancel_time'=>time(),'status'=>self::STATUS_CANCEL]);

    }
    //获取 商品ID
    public static function getGoodsId($id)
    {
        $info = self::commonQuery(self::TABLE_NAME,self::CACHE_EXPIRE_LEVEL_4)
            ->where(['order_info_id'=>$id])
            ->find();
        return empty($info)?0:$info['goods_id'];
    }
}

